package com.dragon.app.concurrent;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: longtao
 * @Date: 2019/5/12
 * @Version: 1.0
 * @Description:
 */
public class ThreadPoolUtils {
    /**
     *
     */
    private static ExecutorService defaultExecutorService = null;

    /**
     *
     */
    private static final String threadNamePrefix = "MyThreadPool-Thread-";


    /**
     * get a default ExecutorService
     *
     * @return
     */
    public static ExecutorService getExecutorService() {
        if (defaultExecutorService == null) {
            synchronized (ThreadPoolUtils.class) {
                if (defaultExecutorService == null) {
                    defaultExecutorService = new ThreadPoolExecutor(2, 16, 30, TimeUnit.SECONDS,
                            new LinkedBlockingQueue<>(10),
                            new MyThreadFactory(),
                            new ThreadPoolExecutor.DiscardPolicy());
                }
            }
        }
        return defaultExecutorService;
    }


    /**
     * a custom ThreadFactory
     */
    public static class MyThreadFactory implements ThreadFactory {
        private AtomicInteger count = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, threadNamePrefix + count.getAndIncrement());
        }
    }

}
